/* 
 * The MIT License
 *
 * Copyright 2014 Venkat Ram Akkineni.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.netbeans.modules.tfsnb.core;

import com.microsoft.tfs.core.TFSConnection;
import com.microsoft.tfs.core.TFSTeamProjectCollection;
import com.microsoft.tfs.core.exceptions.TECoreException;
import com.microsoft.tfs.core.exceptions.TFSUnauthorizedException;
import com.microsoft.tfs.core.httpclient.Credentials;
import com.microsoft.tfs.core.httpclient.UsernamePasswordCredentials;
import com.microsoft.tfs.core.util.URIUtils;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.netbeans.modules.tfsnb.core.ExceptionUtil.getRootException;

import static org.netbeans.modules.tfsnb.core.Util.isNotEmpty;

/**
 *
 * @author Venkat Ram Akkineni
 */
public class AddTFSConnectionPanelController {
    
    private String name;
    private String path;
    private String portNumber;
    private String serverUrl;
    private ConnectionSettings.PROTOCOL protocol;
    private boolean saveCredentials;
    private String username;
    private char[] password;    
    private TFSConnectionRegistry connectionRegistry = TFSConnectionRegistry.getInstance();
    private ConnectionService connectionService;
    
    private static final Logger LOG = Logger.getLogger(AddTFSConnectionPanelController.class.getName());

    public AddTFSConnectionPanelController() {
        connectionService = new ConnectionService();
    }
    
    public AddTFSConnectionPanelController(final ConnectionSettings cs) {
        this();
        setName(cs.getName());
        setPath(cs.getPath());
        setPortNumber(cs.getPortNumber());
        setServerUrl(cs.getServerUrl());
        setSaveCredentials(false);
        setProtocol(cs.getProtocol());
        setUsername(cs.getUsername());
        setPassword(cs.getPassword());
    }
    
    public boolean validate() {
        return isNotEmpty(name) && isNotEmpty(path) && isNotEmpty(portNumber) && isNotEmpty(serverUrl) && protocol != null && username.contains("\\");
    }
    
    public void store() {
        
    }
    
    public String testConnection() {        
        Credentials credentials = new UsernamePasswordCredentials(username, new String(password));        
        TFSConnection connection = null;
        TFSTeamProjectCollection tfsTeamProjectCollection;
               
        tfsTeamProjectCollection = new TFSTeamProjectCollection(URIUtils.newURI(getUrlPreview()), credentials);        
        String message = "success";
        try {
            tfsTeamProjectCollection.authenticate();
            tfsTeamProjectCollection.close();
        } catch(TFSUnauthorizedException e) {
            message = "Connection failed: " + e.getMessage();
            LOG.log(Level.INFO, message);
        } catch(TECoreException e) {
            Throwable root = getRootException(e);
            message = root.getClass().equals(SocketException.class) ? "Possible bad protocol": e.getMessage();
            message = "Connection failed: " + message;
            LOG.log(Level.INFO, message);
        }
        
        return message;
    }
    
    public String getUrlPreview() {
        String urlPreview = "";
        if(protocol != null) {
            urlPreview += protocol.toString().toLowerCase();
        }        
        if(isNotEmpty(serverUrl)) {
            urlPreview += "://" + serverUrl;
        }        
        if(isNotEmpty(portNumber)) {
            urlPreview += ":" + portNumber;
        }
        if(isNotEmpty(path)) {
            urlPreview += "/" + path;
        }
                
        return urlPreview;
    }
    
    public ConnectionSettings parseComponents(final String serverUrl) {
        return null;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getPortNumber() {
        return portNumber;
    }

    public void setPortNumber(String PortNumber) {
        this.portNumber = PortNumber;
    }

    public String getServerUrl() {
        return serverUrl;
    }

    public void setServerUrl(String serverUrl) {
        this.serverUrl = serverUrl;
    }

    public ConnectionSettings.PROTOCOL getProtocol() {
        return protocol;
    }

    public void setProtocol(ConnectionSettings.PROTOCOL protocol) {
        this.protocol = protocol;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public char[] getPassword() {
        return password;
    }

    public void setPassword(char[] password) {
        this.password = password;
    }

    public boolean isSaveCredentials() {
        return saveCredentials;
    }

    public void setSaveCredentials(boolean saveCredentials) {
        this.saveCredentials = saveCredentials;
    }

    public void saveConnection() throws Exception {
        ConnectionSettings conn = null;
        if(saveCredentials) {
            conn = new ConnectionSettings(name, serverUrl, path, portNumber, protocol, username, new String(password), saveCredentials);            
        } else {
            conn = new ConnectionSettings(name, serverUrl, path, portNumber, protocol, saveCredentials);
        }
        if(conn.validate()) {
            connectionRegistry.addConnection(conn);
        } else {
            throw new Exception("Failed to save the new connection.");
        }
    }
    
    public void updateConnection(final ConnectionSettings cs) throws Exception {       
        
        cs.setName(name);
        cs.setServerUrl(serverUrl);
        cs.setPath(path);
        cs.setPortNumber(portNumber);
        cs.setProtocol(protocol);        
        cs.setSaveCredentials(saveCredentials);
        
        if(saveCredentials) {
            cs.setUsername(username);
            cs.setPassword(password);
        }
        
        if(cs.validate()) {
            connectionService.update(cs);
        } else {
            throw new Exception("Failed to save the connection.");
        }
    }
        
}
